<template>
    <view>
        <block v-for="(item, index) in pageData" :key="index">
            <navBar
                :title="item.compCont.title"
                :bgColor="item.compCont.bgColor"
                :color="item.compCont.color"
                :searchShow="item.compCont.search"
                :content="item.compCont.content"
                :img="item.compCont.img"
                :marginLeft="item.compCont.marginLeft"
                @toAddress="getAddress = true"
                v-if="(item.compCont.style == 1 || (item.compCont.style == 2 && isShow)) && item.type == 'header'"
                isTabbar
            ></navBar>

            <!-- 搜索图标-顶部导航配置 -->
            <view
                class="search flexac white"
                :style="{ 'background-color': item.compCont.searchBgColor, top }"
                @click="toUrl('/pages/classify/search?mode=' + (item.compCont.mode || ''))"
                v-if="item.type == 'header' && item.compCont.search"
            >
                <view class="iconfont icon-sousuokuang1 white size28"></view>
            </view>

            <Bannel v-if="item.type == 'banner'" :pageData="item.compCont" :searchData="item.searchData" :isImmerse="pageData[0].compCont.style"></Bannel>
            <tabItem v-if="item.type == 'nav'" :pageData="item.compCont"></tabItem>
            <searchBor v-if="item.type == 'search'" :pageData="item.compCont"></searchBor>
            <coupon v-if="item.type == 'coupon'" :pageData="item.compCont"></coupon>
            <VideoList v-if="item.type == 'video'" :pageData="item.compCont" @playVideo="pauseAudio" @endVideo="playAudio"></VideoList>
            <notice v-if="item.type == 'notice'" :pageData="item.compCont"></notice>
            <product v-if="item.type == 'goodsDisplay'" :pageData="item.compCont" ref="goodsDisplay"></product>
            <adv v-if="item.type == 'advertisement'" :pageData="item.compCont"></adv>
            <fromList v-if="item.type == 'form'" :title="item.title" :pageData="item.compCont"></fromList>
            <textTitle v-if="item.type == 'text'" :pageData="item.compCont"></textTitle>
            <parseContent v-if="item.type == 'richText'" :pageData="item.compCont"></parseContent>
            <tabs v-if="item.type == 'goodsGroup'" :pageData="item.compCont" ref="tabs"></tabs>
            <ArticleList v-if="item.type == 'article'" :title="item.title" :pageData="item.compCont" ref="article"></ArticleList>
            <divider v-if="item.type == 'divider'" :pageData="item.compCont"></divider>
            <hotZone v-if="item.type == 'hotZone'" :pageData="item.compCont" :isImmerse="pageData[0].compCont.style" :table_bar="table_bar"></hotZone>
            <seckill v-if="item.type == 'seckill'" :pageData="item.compCont" ref="seckill"></seckill>
            <groupBuy v-if="item.type == 'groupBuy'" :pageData="item.compCont" ref="groupBuy"></groupBuy>
            <practice v-if="item.type == 'answer'" :pageData="item.compCont"></practice>
            <courseList v-if="item.type == 'study'" :pageData="item.compCont"></courseList>
            <bargain v-if="item.type == 'bargain'" :pageData="item.compCont" ref="bargain"></bargain>
            <store v-if="item.type == 'store'" :pageData="item.compCont" ref="store"></store>
            <storeGroup v-if="item.type == 'storeGroup'" :pageData="item.compCont" ref="storeGroup"></storeGroup>
            <audioPlay v-if="item.type == 'audio'" :pageData="item.compCont" ref="audioPlay"></audioPlay>
            <floatWindow v-if="item.type == 'floatWindow'" :pageData="item.compCont"></floatWindow>
        </block>

        <contact :bgColor="prevColor" v-if="pageData && pageData.length"></contact>

        <view class="content" v-if="showPop">
            <view class="advertising">
                <image :src="$imgUrls(beginData.start_img)" mode="aspectFill"></image>
            </view>
            <view class="fiexd_bottom flexac black size26" @click="toPage">
                <text class="m-right4">跳过</text>
                <text>{{ cudTime }}</text>
                <text class="m-left4">S</text>
            </view>
        </view>

        <tabBar :tab="1" v-if="!table_bar.homeHide"></tabBar>
    </view>
</template>

<script>
    import API from '../../api/index.js';
    import { mapState, mapMutations } from 'vuex';
    import startPage from '@/components/home/startPage.vue';
    import navBar from '@/components/navBar/navBar.vue';
    import Bannel from '@/components/home/Bannel.vue';
    import tabItem from '@/components/home/tabItem.vue';
    import searchBor from '@/components/home/searchBor.vue';
    import coupon from '@/components/home/coupon.vue';
    import notice from '@/components/home/notice.vue';
    import VideoList from '@/components/home/VideoList.vue';
    import product from '@/components/home/product.vue';
    import adv from '@/components/home/adv.vue';
    import tabs from '@/components/home/tabs.vue';
    import ArticleList from '@/components/home/ArticleList.vue';
    import divider from '@/components/home/divider.vue';
    import fromList from '@/components/home/fromList.vue';
    import textTitle from '@/components/home/textTitle.vue';
    import parseContent from '@/components/home/parseContent.vue';
    import hotZone from '@/components/home/hotZone.vue';
    import seckill from '@/components/home/seckill.vue';
    import groupBuy from '@/components/home/groupBuy.vue';
    import practice from '@/components/home/practice.vue';
    import courseList from '@/components/home/courseList.vue';
    import SharePoster from '@/components/sharePoster.vue';
    import bargain from '@/components/home/bargain.vue';
    import store from '@/components/home/store.vue';
    import storeGroup from '@/components/home/storeGroup.vue';
    import audioPlay from '@/components/home/audioPlay.vue';
    import floatWindow from '@/components/home/floatWindow.vue';
    export default {
        components: {
            startPage,
            navBar,
            Bannel,
            tabItem,
            searchBor,
            coupon,
            notice,
            VideoList,
            product,
            adv,
            tabs,
            ArticleList,
            divider,
            fromList,
            textTitle,
            parseContent,
            hotZone,
            seckill,
            groupBuy,
            practice,
            courseList,
            SharePoster,
            bargain,
            store,
            storeGroup,
            audioPlay,
            floatWindow
        },
        data() {
            return {
                pageData: [],
                beginData: '',
                cudTime: 3,
                dtime: null,
                showPop: false,
                appId: 'wxe15b8e7c6d24d9eb', // wx0dfa86bb709fd84d  wx1612bec59af00207
                options: '',
                isShow: false,
                prevColor: '',
                isFirst: true,
                getAddress: false, // 从收货地址页返回
                table_bar: ''
            };
        },
        onLoad(opt) {
            console.log('opt', opt);
            this.options = opt;
            if (opt.scene) this.Scenein(opt.scene);
            if (Object.keys(opt).length)
                this.getUser({
                    request: this.options
                });

            // #ifdef MP-WEIXIN
            const info = uni.getAccountInfoSync();
            if (info) this.appId = info.miniProgram.appId;
            API.user.getOpenid();
            // #endif
            this.startUpFc();
        },
        onShow() {
            // 子组件监听页面onShow
            if (this.$refs.article) {
                // 文章列表
                this.$refs.article.forEach((obj) => {
                    obj.getBlockInfo();
                });
            }
            if (this.$refs.tabs) {
                // 商品分组-样式三
                this.$refs.tabs.forEach((obj) => {
                    if (obj.pageData.style == 3) {
                        obj.getBlockInfo();
                    }
                });
            }
            // 首页加载页面不执行
            if (!this.isFirst) this.playAudio();

            if (this.getAddress) this.getOldAddress();
        },
        onHide() {
            this.isFirst = false;
            this.pauseAudio();
        },

        methods: {
            ...mapMutations(['getUser', 'changeTab', 'setPrompt', 'setLaunch', 'setAudio', 'setHome']),
            getNearStore(address_id) {
                // 获取最近的店铺id
                this.$http
                    .post({
                        url: '/zzj_singleSaleApi/storeSortByDistance',
                        data: {
                            address_id
                        }
                    })
                    .then((res) => {
                        if (res.errcode != 100) return this.$Toast(res.msg);
                        let shop_id = res.data;
                        if (this.homeShopId == shop_id) return;
                        this.setHome({
                            homeShopId: shop_id
                        });
                        this.updateComp();
                    });
            },
            getOldAddress() {
                this.$http
                    .post({
                        url: '/SRA_simMallApi/getOldAddress',
                        data: {
                            type: 3
                        }
                    })
                    .then((res) => {
                        if (res.code == 100 && res.data.address_id) {
                            this.setHome({
                                homeAddress: res.data.Aregion + res.data.Aaddress
                            });
                            this.getNearStore(res.data.address_id);
                        } else {
                            if (!this.getAddress) this.geocoder();
                        }
                        this.getAddress = false;
                    });
            },
            async geocoder() {
                await this.$pop.getLocation();
                this.$http
                    .get_ds({
                        url: '/geocoder',
                        data: {
                            postStr: {
                                lon: this.position.longitude,
                                lat: this.position.latitude,
                                ver: 1
                            },
                            type: 'geocode',
                            tk: this.tdkey
                        }
                    })
                    .then((res) => {
                        if (res.status != 0) return;
                        this.setHome({
                            homeAddress: res.result.formatted_address
                        });
                        this.getNearStore('');
                    });
            },
            updateComp() {
                let values = Object.values(this.$refs);
                if (!values.length) return;
                values.forEach((value) => {
                    value.forEach((item) => {
                        if (item.getBlockInfo) item.getBlockInfo();
                    });
                });
            },
            pauseAudio() {
                if (this.$refs.audioPlay) {
                    this.$refs.audioPlay.forEach((obj) => {
                        // 当页播放模式
                        if (!obj.pageData.style || !obj.pageData.global) {
                            if (obj.onPlay) {
                                // 播放中要暂停
                                obj.audioCtx.pause();
                            }
                        }
                    });
                }
            },
            playAudio() {
                if (this.$refs.audioPlay) {
                    this.$refs.audioPlay.forEach((obj) => {
                        if (!obj.pageData.style || !obj.pageData.global) {
                            if (obj.onPlay && obj.audioCtx.paused) {
                                // 恢复播放
                                obj.audioCtx.play();
                            }
                        }
                    });
                }
            },
            diyget() {
                this.$http
                    .get({
                        url: '/newdiy/api/v1/diy/getDiyPage',
                        data: {
                            front: 1,
                            id: 0
                        }
                    })
                    .then((res) => {
                        if (res.status != 200) return;
                        const result = res.data.front_value || [];
                        if (res.data.table_bar) this.table_bar = res.data.table_bar.compCont;
                        let searchData, globalAudio;
                        result.forEach((item, index) => {
                            if (item.type == 'header') searchData = item.compCont;
                            if (item.type == 'banner') item.searchData = searchData;
                            if (item.type == 'audio' && item.compCont.style == 1 && item.compCont.global) globalAudio = true;
                        });
                        this.pageData = result;
                        if (result.length > 2) this.prevColor = result[result.length - 2].compCont.bgColor;
                        if (!globalAudio) this.setAudio();
                        if (searchData.content == 2 && !this.homeShopId) return this.getOldAddress();
                        setTimeout(() => {
                            this.handleLocate();
                        }, 1000);
                    });
            },

            async handleLocate() {
                let lng = this.position.longitude;
                await this.$pop.getLocation();
                if (this.position.longitude != lng) {
                    if (this.$refs.store) {
                        // 门店
                        this.$refs.store.forEach((obj) => {
                            obj.getBlockInfo();
                        });
                    }
                    if (this.$refs.storeGroup) {
                        // 门店分组
                        this.$refs.storeGroup.forEach((obj) => {
                            obj.getBlockInfo();
                        });
                    }
                }
            },

            startUpFc() {
                this.$http
                    .post({
                        url: '/zzj_singleSaleApi/startUp',
                        data: {
                            appid: this.appId,
                            pid: this.options.pid || '', // 私域会员id
                            way: this.options.w || 1 // 直接搜索1 卡片分享2 朋友圈3 海报分享4
                        }
                    })
                    .then((res) => {
                        if (res.errcode != 100) return this.$Toast(res.msg);
                        const result = res.data;
                        this.beginData = result;
                        this.cudTime = result.countdown;
                        const obj = {
                            bid: res.bid,
                            tabBar: res.diy_table_bar ? res.diy_table_bar.compCont : '',
                            logo: result.logo_img,
                            share: result.share,
                            nameDefinition: result.nameDefinition,
                            withdrawal_rules: result.withdrawal_rules,
                            mode: result.mode,
                            startUp: result,
                            color: res.themeConfig.colorVal1,
                            colorVal: res.themeConfig.colorVal2,
                            regInfo: result.regInfo
                        };
                        this.getUser(obj);
                        this.diyget();

                        uni.setStorageSync('bid', res.bid);
                        uni.setStorageSync('shareData', result.share);
                        uni.setStorageSync('mode', result.mode ? result.mode : '0');
                        uni.setStorageSync('startUp', result);
                        getApp().globalData.color = res.themeConfig.colorVal1;
                        getApp().globalData.color_aid = res.themeConfig.colorVal2;
                        // startUp为0开屏广告关闭
                        if (result.startUp != 1) return this.toPage();
                        if (this.launch) this.showPop = true;
                        this.dtime = setInterval(() => {
                            if (this.cudTime > 1) {
                                this.cudTime--;
                            } else {
                                this.toPage();
                            }
                        }, 1000);
                    });
            },

            toPage() {
                clearInterval(this.dtime);
                this.showPop = false;
                if (this.launch)
                    this.setLaunch({
                        launch: false
                    });
                if (!this.options || !this.options.pageType) {
                    // if (this.openAds) this.setPrompt(true)
                    return;
                }
                if (this.options.share_v_id) {
                    uni.setStorageSync('share_v_id', this.options.share_v_id);
                    this.getUser({
                        share_v_id: this.options.share_v_id
                    });
                }
                const { pageType } = this.options;
                let url;
                if (pageType == 3) {
                    // 参团
                    url = '/userPage/group/tuxedo?gid=' + this.options.gid + '&aid=' + this.options.aid + '&group_id=' + this.options.group_id + '&fromShare=1';
                }
                if (pageType == 4) {
                    url = '/otherPage/article/artDetail?artId=' + this.options.artId + '&fromShare=1';
                }
                if (pageType == 5) {
                    url = '/pages/artList/artList?listId=' + this.options.listId + '&fromShare=1';
                }
                if (pageType == 6) {
                    url = '/pages/video/video?goodsid=' + this.options.gid + '&classifyId=' + this.options.cid + '&fromShare=1';
                }
                if (pageType == 7) {
                    // 单商品特价活动
                    url = '/activityPage/bargain_goods/a_single_commodity?act_id=' + this.options.act_id + '&fromShare=1';
                }
                if (pageType == 8) {
                    // 单商品团购
                    url = '/activityPage/group/singleitemliner?act_id=' + this.options.act_id + '&fromShare=1';
                }
                if (pageType == 9) {
                    // 多商品首页
                    url = '/activityPage/bargain_goods/more_goods_page?act_id=' + this.options.act_id + '&fromShare=1';
                }
                if (pageType == 10) {
                    // 分享链接来的 商品详情页（合并版）
                    url = '/pages/goods/goods_detail?goodsid=' + this.options.gid + '&fromShare=1';
                }
                if (pageType == 11) {
                    // 素材详情
                    url = '/privatePage/material/sourceDetail?mid=' + this.options.mid + '&fromShare=1';
                }
                if (pageType == 12) {
                    // 私域首页
                    url = '/privatePage/index/index?fromShare=1';
                }
                if (pageType == 13) {
                    // 素材中心
                    url = '/privatePage/material/center?fromShare=1';
                }
                if (pageType == 14) {
                    // 二维码名片
                    url = '/privatePage/single/codeCard?pid=' + this.options.pid + '&fromShare=1';
                }
                if (pageType == 15) {
                    // 门店首页
                    url = '/pages/store/storeIndex?shop_id=' + this.options.shop_id + '&fromShare=1';
                }
                if (pageType == 16) {
                    // 跳表单（gid代替，不然后台分享需要新增参数）
                    url = '/pages/reserve/formSubmit?ordId=' + this.options.gid + '&fromShare=1';
                }
                if (pageType == 17) {
                    // 跳游戏（cid代替cid，gid代替type,不然后台分享需要新增参数）
                    if (this.options.gid == 'default') {
                        //摇一摇
                        url = '/otherPage/lottery/shark?cid=' + this.options.cid + '&fromShare=1';
                    } else if (this.options.gid == 'marquee') {
                        //跑马灯
                        url = '/otherPage/lottery/good_luck?cid=' + this.options.cid + '&fromShare=1';
                    } else if (this.options.gid == 'slotMachine') {
                        //老虎机
                        url = '/otherPage/lottery/tiger?cid=' + this.options.cid + '&fromShare=1';
                    } else if (this.options.gid == 'bigWheel') {
                        //大转盘
                        url = '/otherPage/lottery/roulette?cid=' + this.options.cid + '&fromShare=1';
                    } else if (this.options.gid == 'blindBox') {
                        // 盲盒
                        url = '/otherPage/lottery/blindBox?cid=' + this.options.cid + '&fromShare=1';
                    } else if (this.options.gid == 'twistedEgg') {
                        // 扭蛋
                        url = '/otherPage/lottery/gashapon?cid=' + this.options.cid + '&fromShare=1';
                    } else if (this.options.gid == 'drawCard') {
                        // 抽卡
                        url = '/otherPage/lottery/drawCard?cid=' + this.options.cid + '&fromShare=1';
                    }
                }
                if (pageType == 18) {
                    // 芬霄中心
                    url = '/userPage/distributors/fenxiaoCenter?fromShare=1';
                }
                if (pageType == 19) {
                    // 免费领取课程
                    url = '/orderPage/coursePay/freeCourse?id=' + this.options.id;
                }
                if (pageType == 20) {
                    // 免费领取课程
                    url = '/moneyPage/capital/myMoney?fromShare=1';
                }
                if (pageType == 21) {
                    // 课程目录
                    url = `/answer/play?goods_id=${this.options.gid}&fromShare=1`;
                }
                if (pageType == 22) {
                    // 扫码点餐
                    url = `/otherPage/custom/placeOrder?tid=${this.options.tid}&fromShare=1`;
                }
                if (pageType == 23) {
                    // 优惠券领取
                    url = `/activityPage/getCoupons?tid=${this.options.tid}&fromShare=1`;
                }
                if (pageType == 24) {
                    // diy内页
                    url = `/otherPage/custom/index?id=${this.options.id}&fromShare=1`;
                }
                if (pageType == 25) {
                    // 砍价分享
                    url = `/activityPage/bargain/shareDetail?record_id=${this.options.record_id}&fromShare=1`;
                }
                if (pageType == 26) {
                    // 扫码进群
                    url = `/otherPage/custom/addGroup?id=${this.options.id}&fromShare=1`;
                }
                if (pageType == 30) {
                    //仓库分享
                    url = `/warehouse/chick?ids=${this.options.giveId}&userkey=${this.options.userkey}`;
                }
                if (pageType == 31) {
                    // 取号
                    url = `/queueup/takeNumber?shop_id=${this.options.id}&fromShare=1`;
                }
                if (pageType == 32) {
                    // 次卡
                    url = `/subCard/shareClaim?id=${this.options.id}&fromShare=1`;
                }
                if (pageType == 33) {
                    // 活动
                    url = `/activityPage/seckill/activity?act_id=${this.options.id}&fromShare=1`;
                }
                uni.reLaunch({
                    url: url
                });
            },

            Scenein(scene) {
                let sceneInfo = decodeURIComponent(scene).split('&');
                let sceneType = {};
                sceneInfo.forEach((item) => {
                    let pram = item.split('=');
                    sceneType[pram[0]] = pram[1];
                });
                let opt = {
                    ...sceneType,
                    pageType: '',
                    share_v_id: ''
                };

                if (sceneType.gid) opt.artId = sceneType.gid;
                if (sceneType.p) opt.pageType = sceneType.p;
                if (sceneType.sid) opt.share_v_id = sceneType.sid;
                if (sceneType.pid) opt.share_v_id = sceneType.pid;
                if (sceneType.m) opt.mid = sceneType.m; // 素材id
                if (sceneType.id) opt.shop_id = sceneType.id;
                this.options = opt;
                if (opt.share_v_id) {
                    uni.setStorageSync('share_v_id', opt.share_v_id);
                    this.getUser({
                        share_v_id: opt.share_v_id
                    });
                }
                console.log('options', this.options);
                this.getUser({
                    request: this.options
                });
            }
        },

        computed: {
            ...mapState(['share', 'vid', 'System', 'navHeight', 'launch', 'position', 'openAds', 'tdkey', 'homeShopId']),
            top() {
                // 搜索图标fixed定位top值
                return this.System.statusBarHeight + this.navHeight / 2 + 'px';
            }
        },
        onShareAppMessage(res) {
            let share = this.share;
            return {
                title: share.title,
                desc: share.desc,
                path: `/pages/index/index?share_v_id=${this.vid}&pageType=999`,
                imageUrl: share.imageUrl
            };
        },
        onShareTimeline() {
            let share = this.share;
            return {
                title: share.title,
                imageUrl: share.imageUrl
            };
        },

        // 监听滚动
        onPageScroll(e) {
            if (e.scrollTop > 100) {
                this.isShow = true;
            } else {
                this.isShow = false;
            }
        }
    };
</script>

<style lang="scss" scoped>
    .content {
        width: 100%;
        height: 100vh;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 88888;
        background: #ffffff;
    }

    .advertising {
        width: 100%;
        height: 100%;
        position: absolute;

        image {
            width: 100%;
            height: 100%;
        }
    }

    .fiexd_bottom {
        width: 160rpx;
        height: 70rpx;
        border-radius: 35rpx;
        position: absolute;
        bottom: 100rpx;
        right: 20rpx;
        background: #ffffff;
    }

    .search {
        width: 66rpx;
        height: 66rpx;
        border-radius: 50%;
        position: fixed;
        margin-top: -33rpx;
        left: 24rpx;
        z-index: 2000;
    }

    ::v-deep .myCut .u-line-progress__line {
        // 我的砍价
        background: linear-gradient(-90deg, #f41c26, #ffa35e);
    }
</style>
